﻿using FluentValidation;
using SDF.Core.Data;
using SDF.Data;
using SDF.Plugin.Misc.DynamicEntity.Domain;
using SDF.Plugin.Misc.DynamicEntity.Models;
using SDF.Services.Localization;
using SDF.Web.Framework.Validators;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SDF.Plugin.Misc.DynamicEntity.Validators.DynamicEntity
{
    public class DynamicEntityItemValidator : BaseSDFValidator<DynamicEntityItemModel>
    {
        public DynamicEntityItemValidator(ILocalizationService localizationService, IDbContext dbContext, IRepository<DynamicEntityItem> entityRepository)
        {
            RuleFor(x => x.CodeName)
                .NotEmpty()
                .WithMessage(localizationService.GetResource("Plugins.Misc.DynamicEntity.CodeName.Required"));

            RuleFor(x => x.Name)
                .NotEmpty()
                .WithMessage(localizationService.GetResource("Plugins.Misc.DynamicEntity.Name.Required"));

            RuleFor(x => x.CodeName)
                .Must((model, x) =>
                {
                    //DynamicEntity的CodeName不能重复
                    return entityRepository.Table.Any(p => p.HeaderId.Equals(model.HeaderId) && p.CodeName.Equals(x) && p.Id != model.Id) == false;
                }).WithMessage(localizationService.GetResource("Plugins.Misc.DynamicEntity.CodeName.Unique"));

            SetStringPropertiesMaxLength<DynamicEntityItemModel>(dbContext);
        }
    }
}